package per.hx.bs.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.hx.bs.entity.WxUserDO;
import per.hx.bs.service.WxUserService;
import per.hx.bs.service.WxService;
import per.hx.bs.utils.JWT;
import per.hx.bs.service.RedisService;
import per.hx.bs.utils.WxUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.UUID;

/**
 * @author HuXing
 * @date 2018/5/10  17:03
 */
@Service
public class WxServiceImpl implements WxService {

    private final
    WxUtil wxUtil;

    private final RedisService redisService;

    private final
    WxUserService wxUserService;

    @Autowired
    public WxServiceImpl(WxUtil wxUtil, WxUserService wxUserService, RedisService redisService) {
        this.wxUtil = wxUtil;
        this.wxUserService = wxUserService;
        this.redisService = redisService;
    }

    @Override
    public String getToken(String code) {
        try {
            URL url = new URL(wxUtil.setURL(code));
            URLConnection urlConnection = url.openConnection();
            urlConnection.setUseCaches(true);
            urlConnection.setConnectTimeout(2000);
            urlConnection.setReadTimeout(2000);
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.connect();

            //4.2获取响应正文
            BufferedReader reader;
            StringBuffer resultBuffer = new StringBuffer();
            String tempLine;

            reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            reader.close();
            System.out.println(resultBuffer);
            Map<String, Object> map = JSON.parseObject(resultBuffer.toString());
            String key = null;
            if (!map.isEmpty()) {
                String openid = (String) map.get("openid");
                key = UUID.randomUUID().toString().replaceAll("-", "");
                System.out.println(key);
                WxUserDO wxUserDO = new WxUserDO();
                wxUserDO.setOpenId(openid);
                if (wxUserService.getByOpenId(openid) == null) {
                    wxUserService.insert(wxUserDO);
                }
                WxUserDO wxUserDO1 = wxUserService.getByOpenId(openid);
                String token = JWT.sign(wxUserDO1, 24L * 3600L);
                redisService.set(key, token, 24L * 3600L);
            }
            return key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
